<template>
  <div class="addShop">
    <el-dialog
      :before-close="handClose"
      center
      width="60%"
      :title="title"
      :visible.sync="off"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        size="mini"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="storeName">
              <el-input v-model.trim="ruleForm.storeName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期" prop="validityTime">
              <el-date-picker v-model="ruleForm.validityTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺营业时间" prop="businessHours">
              <el-time-picker
                is-range
                v-model="ruleForm.businessHours"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
              ></el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺信息" prop="shopNotices">
              <el-input v-model.trim="ruleForm.shopNotices"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="linkman">
              <el-input v-model.trim="ruleForm.linkman"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺分类:" prop="categoryId">
              <el-select v-model="ruleForm.categoryId">
                <el-option
                  v-for="(item, index) in shopType"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="mobile">
              <el-input v-model.trim="ruleForm.mobile"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺详细地址:" prop="address">
              <el-input v-model.trim="ruleForm.address"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起送价格" prop="price">
              <el-input v-model.number="ruleForm.price"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="营业执照:" prop="businessLicence">
              <upload @selectImg="selectImg" ref="pic1" kind="businessPic"></upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="手持照片" prop="picture">
              <upload @selectImg="selectImg" ref="pic2" kind="handPic"></upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="店铺背景图" prop="bgPicture">
              <upload @selectImg="selectImg" ref="pic3" kind="shopPic"></upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="map" :style="{width:'100%',height:'500px'}">
        <div class="search">
          <div class="title">请输入关键字</div>
            <el-amap-search-box
              class="search-box"
              :search-option="searchOption"
              :on-search-result="onSearchResult"
            ></el-amap-search-box>
        </div>
        <el-amap :key="mapKey" vid="amap" :plugin="plugin" class="amap-demo" :center="center">
          <!-- 在地图上标记点 -->
          <!-- <el-amap-marker v-for="(marker,index) in markers" :key="index" :position="marker"></el-amap-marker> -->
          <!-- 坐标点 -->
          <el-amap-marker vid="amapDemo" :position="center"></el-amap-marker>
           <!-- 当前所在位置的窗口 -->
           <el-amap-info-window
            :position="currentWindow.position"
            :content="currentWindow.content"
            :visible="currentWindow.visible"
            :events="currentWindow.events"
          ></el-amap-info-window>
          <!-- 文字 -->
         <!-- <el-amap-text
            v-for="(text,index) in texts"
            :text="text.text"
            :key="index"
            :offset="text.offset"
            :position="text.position"
            :events="text.events"
          ></el-amap-text> -->
        </el-amap>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="create">立即创建</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addShop } from "@/api/supermarket/shop.js";
import * as util from "@/util/util.js";
export default {
  name: "addShop",
  props: {
    off: {
      type: Boolean
    },
    rowData: {
      type: Object
    },
    title: {
      type: String
    }
  },
  components: {
    upload: () => import("./upload")
  },
  watch: {
    off(val) {
      if (val) {
        this.$nextTick(() => {
          if(this.title == "新增店铺"){
            this.$refs.pic1.recoverBorder();
            this.$refs.pic2.recoverBorder();
            this.$refs.pic3.recoverBorder();
          }
          if(this.title == "修改店铺"){
            console.log(this.$refs.pic);
            this.$refs.pic1.setPic(this.rowData);
            this.$refs.pic2.setPic(this.rowData);
            this.$refs.pic3.setPic(this.rowData);
            this.$refs.pic1.removeBorder();
            this.$refs.pic2.removeBorder();
            this.$refs.pic3.removeBorder();
            this.ruleForm.address = this.rowData.address;
            this.ruleForm.businessHours.push(util.timestampToTime(this.rowData.startTime), util.timestampToTime(this.rowData.endTime));
            this.ruleForm.storeName = this.rowData.storeName;
            this.ruleForm.categoryId = this.rowData.categoryId;
            this.ruleForm.endTime= this.rowData.address;
            this.center = [this.rowData.latitude, this.rowData.longitude];
            this.ruleForm.linkman= this.rowData.linkman;
            this.ruleForm.phone= this.rowData.phone;
            this.ruleForm.price= this.rowData.price;
            this.ruleForm.shopNotices= this.rowData.shopNotices;
            this.ruleForm.businessHours= this.rowData.businessHours;
            this.ruleForm.validityTime= this.rowData.validityTime;
          }
          ++this.mapKey; //重新渲染组件
        });
      }
    }
  },
  data() {
    var self = this;
    return {
      mapKey: 1,
      // 放置文字
      texts: [
        {
          position: [87.59701,43.88269], 
          text: `<img style="width:50px;" src="http://imgsa.baidu.com/exp/w=500/sign=ce843cf58282b9013dadc333438ca97e/10dfa9ec8a13632763a8d5e1998fa0ec09fac79e.jpg"><p>探索宝藏的第一个线索！</p>`,
          offset: [0, 0],
          events: {
            click: () => {
              alert("click text");
            }
          }
        }
      ],
       // 当前窗口
      currentWindow: {
          position: [87.59701,43.88269], //纬度,经度
          content: `<img style="width:50px;" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543494665847&di=152e6f241b64580684a1c048ec9acd7e&imgtype=0&src=http%3A%2F%2Fp0.so.qhmsg.com%2Ft017668631465b251d5.gif"><p style="color:red">Hi！  马优晨，我在这里呢 ！</p>`,
          visible: true,
          events: {
            close() {
              console.log("关闭窗口一！");
            }
          }
      },
      mapCenter: [121.40996, 31.197646],
      makerConf: {
        position: [121.59996, 31.197646],
        content: ""
      },
      markers: [
        [121.49996, 31.297646],
        [121.40018, 31.197622],
        [121.49991, 31.207649]
      ],
      searchOption: {
        city: "乌鲁木齐",
        citylimit: false
      },
      center: [121.59996, 31.197646],
      lng: 0,
      lat: 0,
      loaded: false,
      plugin: [
        "ToolBar",
        {
          pName: "MapType",
          defaultType: 0,
          events: {
            init(o) {
              console.log(o);
            }
          }
        },
        {
          pName: "Scale",
          events: {
            init(instance) {
              console.log(instance);
            }
          }
        },
        {
          pName: "OverView",
          events: {
            init(instance) {
              console.log(instance);
            }
          }
        },
        {
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 100, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: "RB", //定位按钮停靠位置，默认：'LB'，左下角
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
          extensions: "all",
          pName: "Geolocation",
          events: {
            init(o) {
              //定位到城市
              // o.getCityInfo((status, result) => {
              //   console.log("result查询城市", result);
              //   if(result){
              //     self.lng = result.center[0];
              //     self.lat = result.center[1];
              //     self.center = [self.lng, self.lat];
              //     self.loaded = true;
              //     // self.$nextTick();
              //   }
              // }),
              // o 是高德地图定位插件实例(会失败)
              o.getCurrentPosition((status, result) => {
                console.log("result定位", result);
                console.log(self.center);
                if (result && result.position) {
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.center = [self.lng, self.lat];
                  // self.currentWindow.position = [self.lng, self.lat];
                  console.log(self.currentWindow);
                  // self.loaded = true;
                  self.$nextTick();
                }
              });
            }
          }
        }
      ],
      shopType: [
        { label: "休闲零食", value: "1" },
        { label: "水果", value: "2" },
        { label: "蔬菜", value: "3" }
      ],
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        address: [
          { required: true, message: "地址不能为空", trigger: "change" }
        ],
        bgPicture: [
          { required: true, message: "背景图片不能为空", trigger: "change" }
        ],
        businessLicence: [
          { required: true, message: "营业执照不能为空", trigger: "blur" }
        ],
        businessHours: [
          { required: true, message: "营业时间不能为空", trigger: "blur" }
        ],
        shopNotices: [
          { required: true, message: "商家信息不能为空", trigger: "blur" }
        ],
        validityTime: [
          { required: true, message: "有效期不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "起送价格不能为空", trigger: "blur" }
        ],
        phone: [{ required: true, message: "电话不能为空", trigger: "blur" }],
        categoryId: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ]
      },
      ruleForm: {
        address: "",
        bgPicture: "",
        businessLicence: "",
        categoryId: "",
        endTime: "",
        latitude: "",
        linkman: "",
        longitude: "",
        phone: "",
        picture: "",
        price: "",
        shopNotices: "",
        businessHours: [],
        validityTime: ""
      }
    };
  },
  methods: {
     // 搜索框输入
    onSearchResult(pois) {
      console.log(pois, "123456789");
      let me = this;
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        var poi = pois[0];
        let lng = poi["lng"];
        let lat = poi["lat"];
        me.center = [lng, lat];
        me.makerConf.position = [lng, lat];
        me.list = pois;
        pois.forEach(poi => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          this.markers.push([poi.lng, poi.lat]);
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.mapCenter = [center.lng, center.lat];
      }
    },
    selectImg(data, kind) {
      console.log(data, kind);
      if (kind == "businessPic") {
        this.ruleForm.businessLicence = data.businessLicence;
      } else if (kind == "handPic") {
        this.ruleForm.picture = data.picture;
      } else if (kind == "shopPic") {
        this.ruleForm.bgPicture = data.bgPicture;
      }
    },
    handClose() {
      this.$emit("update:off", false);
      this.$refs.pic1.clearImg();
      this.$refs.pic2.clearImg();
      this.$refs.pic3.clearImg();
    },
    create() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) {
          return;
        } else {
          this.ruleForm.startTime = this.ruleForm.businessHours[0];
          this.ruleForm.endTime = this.ruleForm.businessHours[1];
          [this.ruleForm.latitude, this.ruleForm.longitude] = this.center;
          addShop(this.ruleForm).then(
            res => {
              console.log("res新增店铺成功", res);
              this.$message({
                type: "success",
                message: "新增店铺成功"
              });
              this.$emit("update:off", false);
              this.$parent.getList();
              this.$refs.ruleForm.resetFields();
              console.log(this.$refs.pic);
              this.$refs.pic1.clearImg();
              this.$refs.pic2.clearImg();
              this.$refs.pic3.clearImg();
            },
            err => {}
          );
        }
      });
    }
  }
};
</script>

<style scoped lang="less">
.map{
  position: relative;
  .search{
    position: absolute;
    left: 90px;
    top: 20px;
    width: auto;
    height: 72px;
    padding: 20px;
    background: #fff;
    z-index: 99999;
  }
  /deep/.search-box-wrapper{
    border: 1px solid #ccc;
  }
}
</style>